<?php

/**
 * Created by PhpStorm.
 * User: qinlu
 * Date: 2018/7/26
 * Time: 10:19
 */
namespace Api\Controller;
use Think\Controller;
class ShopController extends BaseController
{
	
    //店铺入住申请
    public function add()
    {
        #日志
        doLog("入驻申请--".json_encode(I('*')),"shop_add");
        $user_id = $this->user_id; 
        // 查询本人名下账户
        $select_shop_data = M('shop')->where(['user_id'=>$user_id])->find();
		if(count($select_shop_data) > 1 && $select_shop_data['shop_status'] != 1){
			$this->returnInfo('-1', '此账号已经有开店信息');
		}
		$shop_name = trim(I('shop_name'));
		if(!$shop_name){
		    $this->returnInfo(-1, '店铺名称不能为空');
        }
		// 查询重名店铺
		if(M('shop')->where(['shop_name'=>$shop_name])->find()){
			$this->returnInfo('-1', '店铺名称重复');
		}
		// 查询当前用户信息
		$user_data = M('users')->where(['user_id'=> $user_id])->find();
		if(!$user_data){
			$this->returnInfo('-1', '用户信息缺失');
		}
		$shop_tel = I('shop_tel');
		if(!check_mobile($shop_tel)){
			$this->returnInfo('-1', '手机号码格式不符合');
		}
		// 查询手机号是否可用
		$shop_tel_data = M('shop')->where(['shop_tel'=> $shop_tel])->find();
		if($shop_tel_data){
			$this->returnInfo('-1', '手机号已经使用');
		}
		
		
		$shop_type = 0;// 店铺类型
		$shop_bond = 0;// 店铺保证金
		$shop_status = 0;// 店铺状态
		$create_time = time();
		$shop_intro = '';// 店铺简介
		$isvalid = 1; // 是否有效
		$update_time = time();
		$shop_user = I('shop_user');// 联系人
		$license_name = I('license_name');// 营业执照名称
		$license_img = I('license_img');// 营业执照照片
		$sc_num = I('sc_num');// 收藏数量
		$license_number = I('license_number');// 统一社会信用代码
		$fee_freepost = 0;// 满多少包邮（元） 0不免邮费
		$shop_address_street = I('shop_address_street');// 店铺详细地址
		$shop_address_city = I('shop_address_city');// 省市区
		$shop_head_img = I('shop_head_img');// 店铺logo
		$license_address_street = '';// 营业执照所在街道
		$license_address_city = '';// 营业执照所在省市
		$shop_bei_img = '';// 店铺背景
        $longitude  = I('longitude', -1, 'floatval');//经度
        $latitude  = I('latitude', -1, 'floatval');//纬度
        $goods_type  = I('goods_type', 0, 'intval');//商品类型
        if($longitude < 0 || $latitude < 0){
            $this->returnInfo('-1', '经纬度数据有误');
        }
        if(!in_array($goods_type, array(0, 1))){
            $this->returnInfo('-1', '渠道商品类型有误');
        }
        $city_name = I('city_name', '', 'trim');
        $area_name = I('area_name', '', 'trim');
		
		$shop['shop_name'] = $shop_name;
		$shop['shop_user'] = $shop_user;
		$shop['shop_tel'] = $shop_tel;
		$shop['shop_type'] = $shop_type;
		$shop['shop_bond'] = $shop_bond;
		$shop['shop_status'] = $shop_status;
		$shop['create_time'] = $create_time;
		$shop['shop_intro'] = $shop_intro;
		$shop['update_time'] = $update_time;
		$shop['isvalid'] = $isvalid;
		$shop['shop_address_street'] = $shop_address_street;
		$shop['shop_address_city'] = $shop_address_city;
		$shop['shop_head_img'] = $shop_head_img;
		$shop['license_name'] = $license_name;
		$shop['license_img'] = $license_img;
		$shop['license_address_street'] = $license_address_street;
		$shop['license_address_city'] = $license_address_city;
		$shop['user_id'] = $user_id;
		$shop['shop_bei_img'] = $shop_bei_img;
		$shop['license_number'] = $license_number;
        $shop['longitude'] = $longitude;
        $shop['latitude'] = $latitude;
        $shop['goods_type'] = $goods_type;
        $shop['city_name'] = $city_name;
        $shop['area_name'] = $area_name;
        
		$res = M('shop')->add($shop);

		if ($res) {
		    $this->returnInfo('1', '资料已成功上传,我们会在48小时内完成审核，并以短信的形式通知到您', $res);
		} else {
		    $this->returnInfo('-1', '资料上传失败');
		}
    }
	
	//店铺登录密码维护
	public function saveShopPassword()
	{
	    #日志
	    doLog("店铺密码维护--".json_encode(I()),"save_shop_password");
	    $user_id = $this->user_id; 
		$where['shop_status'] = 2;
		$where['isvalid'] = 1;
		$where['user_id'] = $user_id;
		// 查询本人名下账户
	    $select_shop_data = M('shop')->where($where)->find();
		if(!$select_shop_data){
			$this->returnInfo('-1', '店铺信息不可修改');
		}
		$password = I('password');// 密码1
		$password_check = I('password_check');// 密码2
		if(\md5($password) != \md5($password_check)){
			$this->returnInfo('-1', '两次密码不一致');
		}
		// 查询店铺管理员账号
		$select_admin_data = M('admin')->where(['user_id'=>$user_id])->find();
		if(!$select_admin_data){
			$this->returnInfo('-1', '店铺账户异常');
		}
		
		$save_admin_data['password'] = encrypt($password);
		$save_admin_data['last_login'] = time();
		
		if (M('admin')->where(array('admin_id' => $select_admin_data['admin_id']))->save($save_admin_data)) {
		    $this->returnInfo('1', '修改成功', $res);
		} else {
		    $this->returnInfo('-1', '修改失败');
		}
	}

    /**
     *  店铺协议
     */
    public function agreement()
    {
        $where['key'] = "店铺入驻";
        $agreement = M('agreement')->field('value')->where($where)->find();
        $this->returnInfo('1', '店铺入驻协议获取成功', $agreement);
    }

    /**
     *  店铺状态
     */
    public function shopStatus()
    {
        $user_id = $this->user_id;
        $where['user_id'] = $user_id;
        $res_shop = M('shop')->where($where)->find();
		if (!$res_shop){
			$res['status'] = '-1';
		    $this->returnInfo('1', '未申请开店',$res);
		}
		$res['phone'] = $res_shop['shop_tel'];
		$res['login_url'] = SITE_URL;
		
        if ($res_shop['shop_status'] == '2'){
        	$res['status'] = '1';
            $this->returnInfo('1', '成功开店',$res);
        }
        if ($res_shop['shop_status'] == '0'){
        	$res['status'] = '-3';
            $this->returnInfo('1', '信息审核中',$res);
        }
        if ($res_user['shop_status'] == '1'){
			$res['status'] = '-2';
            $this->returnInfo('1', '您的申请被驳回,请重新申请',$res);
		}
    }


    /**
     * 收藏店铺
     */
    public function sc()
    {
        $shop_id = I('shop_id');
        $type = I('type', 0);
        $count = M('shop')->where("id=$shop_id")->count();
        if ($count == 0)
            exit(json_encode(array('status' => 1, 'msg' => '收藏店铺不存在')));
        //删除收藏店铺
        if ($type == 1) {
            M('ShopCollect')->where("user_id = {$this->user_id} and shop_id = $shop_id")->delete();
            M('Shop')->where("id=$shop_id")->setDec('sc_num');
            $this->returnInfo('1', '成功取消收藏', '-1');
        }
        $count = M('ShopCollect')->where("user_id = {$this->user_id} and shop_id = $shop_id")->count();
        if ($count > 0) $this->returnInfo('1', '您已收藏过该店铺');
        $res = M('ShopCollect')->add(array(
            'shop_id' => $shop_id,
            'user_id' => $this->user_id,
            'time' => time(),
        ));
       //更新收藏数量
        M('Shop')->where("id=$shop_id")->setInc('sc_num');
        $this->returnInfo('1', '收藏成功', '1');
    }


    /**
     *用户收藏店铺列表
     */
    public function sclist()
    {
        $user_id = $this->user_id;
        $list = M('ShopCollect as sc')
            ->field('s.id,s.shop_name,s.shop_head_img,s.shop_address_street,s.shop_address_city,s.shop_intro')
            ->join('ln_shop as s on s.id=sc.shop_id')
            ->where("sc.user_id=$user_id")
            ->select();
        foreach($list as $k => &$v)
        {
            $v['shop_head_img'] = parseMediaUrl($v['shop_head_img']);
        }
        $this->returnInfo('1', '获取成功', $list);
    }

    /**
     *店铺详情。
     */
    public function shop_info()
    {
        $user_id = $this->user_id ? $this->user_id : 0;
        $shop_id = I('shop_id', 0, 'intval');//店铺id 
        $filter_param = array(); // 筛选数组 

        $count = M('shop')->where("id=$shop_id")->count();
        if ($count = 0) {
            $this->returnInfo('0', '店铺没有内容');
        }
        //判断当前用户是否收藏该店铺
		$info['is_collect'] = 0;
        if ($user_id > 0) {
            $where['user_id'] = $user_id;
            $where['shop_id'] = $shop_id;
            $collect = M('shop_collect')->where($where)->find();
            if ($collect) {
                $info['is_collect'] = 1;                
            }
        }
        $shop_info = M('shop as s')
            ->field('s.shop_name,s.shop_type,s.sc_num,s.shop_head_img,s.shop_bei_img,s.user_id,s.shop_address_street,s.shop_address_city')
            ->where("id=$shop_id")
            ->find();
        if( $shop_info )
        {
            $shop_info['shop_head_img'] = parseMediaUrl($shop_info['shop_head_img']);
            $shop_info['shop_bei_img'] = parseMediaUrl($shop_info['shop_bei_img']);
            $info['shop'] = $shop_info;
        }else{
            $info['shop'] = array();
        }
        unset($where);
        $where = array(
            'shop_id' => $shop_id,
            "status" => 1
        );
        $info['gallery'] = M('shop_images')->field('image_url')->where($where)->select();
        foreach ($info['gallery'] as $key => $val) 
        {
            $info['gallery'][$key]['image_url'] = parseMediaUrl($val['image_url']);
        }
        $p = I('p', 1, 'intval');
        $sort_asc = I('sort_asc', 'asc'); // 排序
		
        $price = I('price', ''); // 价钱
        $pagesize = I('pagesize', 10, 'intval');
        $filter_param['shop_id'] = $shop_id; //加入筛选条件中
        $attr && ($filter_param['attr'] = $attr); //加入帅选条件中
        $price && ($filter_param['price'] = $price); //加入帅选条件中

        $pagesize = I('pagesize', 10, 'intval');
        
        #下面一句是干嘛？？？？？？？？？？？？？？
        #$info['goods'] = M('shop as s')->field('g.goods_id,g.goods_name,g.sales_sum,g.shop_price,CONCAT("' . $url . '",g.original_img) original_img,g.market_price,g.goods_remark')->join('ln_goods as g on g.shop_id=s.id')->where("id=$shop_id")->order("goods_id $sort_asc")->page($p, $pagesize)->select();

        $sort_asc = $sort_asc == 'asc' ? 'asc' : 'desc';
		// p($sort_asc);die;
        $orderby_sales_sum = I('orderby_sales_sum');
        $orderby_price = I('orderby_price');
		
        $orderby_default = I('orderby_default');
        $field = 'g.goods_id,g.goods_name,g.sales_sum,g.shop_price,g.original_img,g.market_price,g.goods_remark';
        $whereGoods['s.id'] = $shop_id;
        $whereGoods['g.is_on_sale'] = 1;
        $cate = I('cate_id',0);
        if( $cate )
        {
            $whereGoods['_string'] = "cat_id = {$cate} OR extend_cat_id = {$cate}";
        }
        if ($orderby_sales_sum) {
            $info['goods'] = M('shop as s')->field($field)->join('ln_goods as g on g.shop_id=s.id')->where($whereGoods)->order("sales_sum $sort_asc")->page($p, $pagesize)->select();
        }elseif($orderby_price) {
			// p($sort_asc);die;
            $info['goods'] = M('shop as s')->field($field)->join('ln_goods as g on g.shop_id=s.id')->where($whereGoods)->order("shop_price $sort_asc")->page($p, $pagesize)->select();
        } else {
            $info['goods'] = M('shop as s')->field($field)->join('ln_goods as g on g.shop_id=s.id')->where($whereGoods)->order("goods_id $sort_asc")->page($p, $pagesize)->select();
        }
        foreach($info['goods'] as $ik => &$iv)
        {
            $iv['original_img'] = parseMediaUrl($iv['original_img']);
        }

        // 输出客服
        $info['shop_kefu'] = '';
        if( !empty($info['shop']) )
        {
            $info['shop_kefu'] = (string)$info['shop']['user_id'];
            unset($info['shop']['user_id']);
            $info['shop_kefu_info'] = M('users')->where([
                'user_id' => (int)$info['shop_kefu']
            ])->field('user_id,nickname,head_pic')->find();
            if( $info['shop_kefu_info'] )
            {
                $info['shop_kefu_info']['head_pic'] = \parseMediaUrl($info['shop_kefu_info']['head_pic'] );
            }else{
                $info['shop_kefu_info'] = '';
            }
        }

        C('TOKEN_ON', false);
        $this->returnInfo('1', '获取成功', $info);
    }


    /**
     *店铺简介
     */
    public function shop_desc()
    {
        $shop_id = I('shop_id', 0, 'intval');
        $info = M('shop')
            ->field('shop_name,sc_num,shop_head_img,shop_intro,shop_address_street,shop_address_city, longitude, latitude, goods_type')
            ->where("id=$shop_id")
            ->find();
        if( $info )
        {
            $info['shop_head_img'] = parseMediaUrl($info['shop_head_img']);
        }
        $comment = M('comment')->field('sum(goods_rank) goods_rank,sum(deliver_rank) deliver_rank,sum(service_rank) service_rank')->where("shop_id=$shop_id")->select();
        if ($comment[0]['goods_rank'] !== null && $comment[0]['deliver_rank'] !== null && $comment[0]['service_rank'] !== null) {
            $count = M('comment')->where("shop_id=$shop_id")->count();
            $info['goods_rank'] = ceil($comment[0]['goods_rank'] / $count);
            $info['deliver_rank'] = ceil($comment[0]['deliver_rank'] / $count);
            $info['service_rank'] = ceil($comment[0]['service_rank'] / $count);
        } else {
            $info['goods_rank'] = 5;
            $info['deliver_rank'] = 5;
            $info['service_rank'] = 5;
        }
        $this->returnInfo('1', '获取成功', $info);
    }


    //获取店铺类型
    public function getShopType()
    {
        $shop_type = M('shop_type')->where("isvalid=1 and is_show=1")->select();
        $this->returnInfo('1', '获取店铺分类成功', $shop_type);
    }


    private static function img_uploads($base64_img)
    {
        $base64_img = trim($base64_img);
        $time = time();
        $date = date('Y');
        $date1 = date('m-d');
        $up_dir = './Public/upload/shop/' . $date . '/' . $date1 . '/';

        if (!file_exists($up_dir)) {
            mkdir($up_dir, 0777, true);
        }
        if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_img, $result)) {
            $type = $result[2];
            if (in_array($type, array('pjpeg', 'jpeg', 'jpg', 'gif', 'bmp', 'png'))) {
                $new_file = $up_dir . $time . '.' . $type;
                //var_dump($new_file);exit;
                if (file_put_contents($new_file, base64_decode(str_replace($result[1], '', $base64_img)))) {
                    $img_path = str_replace('./Public/upload/', '', $new_file);
                    return array('status' => 1, 'msg' => "图片上传成功", 'url' => $img_path);
                }
                return array('status' => 2, 'msg' => "图片上传失败");
            }
            //文件类型错误
            return array('status' => 4, 'msg' => "文件类型错误");
        }
        //文件错误
        return array('status' => 3, 'msg' => "文件错误");
    }

}